package com.qf.java2102.qihaonan.hotel.dao.impl;

import com.qf.java2102.qihaonan.hotel.dao.IUserDao;
import com.qf.java2102.qihaonan.hotel.pojo.User;
import com.qf.java2102.qihaonan.hotel.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author qhn
 * @version 1.0
 */
public class UserDaoImpl implements IUserDao {

    private QueryRunner queryRunner = null;


    @Override
    public User findByUsername(String username) throws SQLException {
        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT\n" +
                "  `user_id` userId,\n" +
                "  `username`,\n" +
                "  `password`,\n" +
                "  `nick_name` nickName,\n" +
                "  `is_admin` isAdmin,\n" +
                "  `phone`,\n" +
                "  `gender`,\n" +
                "  `user_status` userStatus,\n" +
                "  `user_create_time` userCreateTime,\n" +
                "  `user_update_time` userUpdateTime,\n" +
                "  `is_delete` isDelete,\n" +
                "  `is_member` isMember,\n" +
                "  `balance`\n" +
                "FROM\n" +
                "  t_user\n" +
                "WHERE username = ?";
        return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanHandler<>(User.class), username);
    }

    @Override
    public User findById(Long userId) throws SQLException {
        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT\n" +
                "  `user_id` userId,\n" +
                "  `username`,\n" +
                "  `password`,\n" +
                "  `nick_name` nickName,\n" +
                "  `is_admin` isAdmin,\n" +
                "  `phone`,\n" +
                "  `gender`,\n" +
                "  `user_status` userStatus,\n" +
                "  `user_create_time` userCreateTime,\n" +
                "  `user_update_time` userUpdateTime,\n" +
                "  `is_delete` isDelete,\n" +
                "  `is_member` isMember,\n" +
                "  `balance`\n" +
                "FROM\n" +
                "  t_user\n" +
                "WHERE user_id = ?";
        return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanHandler<>(User.class), userId);
    }

    @Override
    public int updateBalance(User user) throws SQLException {
        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "UPDATE `t_user` SET `balance` = ? WHERE `user_id` = ?";
        return queryRunner.update(JdbcUtils.getConnection(), sql, user.getBalance(), user.getUserId());
    }
}
